<template>
  <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <p v-else class="avatar-default">
      <img src="../../assets/imgs/iconbg.png" />
      <em>点击上传</em>
    </p>
  </el-upload>
</template>

<script>
import { reactive, toRefs } from 'vue'

export default {
  setup() {
    const state = reactive({
      imageUrl: ''
    })
    const handleAvatarSuccess = (res, file) => {
      state.imageUrl = URL.createObjectURL(file.raw)
    }
    const beforeAvatarUpload = (file) => {
      let types = ['image/jpeg', 'image/jpg', 'image/png']
      const isImage = types.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    }
    return {
      ...toRefs(state),
      handleAvatarSuccess,
      beforeAvatarUpload
    }
  }
}
</script>

<style lang="less">
.avatar-uploader .el-upload {
  border: 1px solid #cacaca;
  border-radius: 20px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 158px;
  height: 158px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-default {
  padding: 0;
  margin: 9px 0 0;
}
.avatar-default em {
  display: block;
  line-height: 26px;
  text-align: center;
  font-style: normal;
  font-size: 16px;
  color: #535353;
}
</style>
